package com.feather.common.db.impl;

import com.feather.common.db.Connector;
import com.feather.common.util.ClassUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author flogyin
 */
public class JdbcConnector implements Connector {
	private boolean	loadedDriver;

	public String	driver;
	public String	url;
	public String	user;
	public String	password;

	@Override
	public Connection getConnection() throws SQLException {
		if (!this.loadedDriver) {
			try {
				ClassUtil.forName(this.driver).newInstance();
				this.loadedDriver = true;
			} catch (ClassNotFoundException ex) {
				throw new SQLException(ex.toString());
			} catch (IllegalAccessException ex) {
				throw new SQLException(ex.toString());
			} catch (InstantiationException ex) {
				throw new SQLException(ex.toString());
			}
		}

		if (this.user != null)
			return DriverManager.getConnection(this.url, this.user, this.password);
		else
			return DriverManager.getConnection(this.url);
	}

	@Override
	public String toString() {
		return this.getClass().getName() + "{driver:" + this.driver + ", url:" + this.url + ", user:" + this.user + "}";
	}
}
